<template>
  <el-dialog v-dialogDrag v-if="popenevTVisible" title="回收重办" :close-on-click-modal="false" :before-close="handleCancel" :visible.sync="popenevTVisible" width="900px">
    <BackRedo ref="backRedoRef"></BackRedo>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="confirmLoading" @click="handleOk">确定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import BackRedo from "../BackRedo.vue";
import { callbackDoc } from "../../api/common/flowsend";
import { useRouter, useRoute } from 'vue-router';
import { useAppStore } from '@/stores/app'; // 假设Pinia store路径

// 响应式数据
const flowstructureunid = ref(null);
const unid = ref(null);
const moduleName = ref(null);
const popenevTVisible = ref(true);
const confirmLoading = ref(false);
const promiseStatus = ref(null);
const backRedoRef = ref(null);

// 使用路由和store
const router = useRouter();
const route = useRoute();
const appStore = useAppStore(); // 获取Pinia store实例

// 方法
const showModal = (data) => {
    flowstructureunid.value = data.flowstructureunid;
    unid.value = data.unid;
    moduleName.value = data.moduleName;
    
    nextTick(() => {
        // 获取办文跟踪数据
        backRedoRef.value.getTableData(unid.value);
    });
    
    // 创建promise
    return new Promise((resolve, reject) => {
        promiseStatus.value = {
            resolve,
            reject
        };
    });
};

const handleOk = () => {
    const records = backRedoRef.value.records;
    confirmLoading.value = true;
    
    if (records.length < 1) {
        appStore.showMessage({ message: '请选择需要回收人员', type: 'error' });
        confirmLoading.value = false;
        return;
    }
    
    const selectedRowKeys = [];
    records.forEach(element => {
        selectedRowKeys.push(element.unid);
    });

    const params = {
        flowstructureunid: flowstructureunid.value,
        moduleName: moduleName.value,
        docIdent: unid.value,
        modifyAcl: true,
        backUnids: selectedRowKeys.join(","),
    };
    
    appStore.showConfirm({
        title: '提示',
        message: '此操作将进行回收, 是否继续?',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        callbackDoc(params).then(res => {
            appStore.showMessage({ message: '回收成功', type: 'success' });
            destroyElement();
            promiseStatus.value.resolve(res);
        }).catch(() => {
            // 错误处理保持为空，与原代码一致
        }).finally(() => {
            confirmLoading.value = false;
        });
    }).catch(() => {
        confirmLoading.value = false;
    });
};

const handleCancel = () => {
    // 清空勾选项
    promiseStatus.value.reject({
        msg: "取消"
    });
    destroyElement();
};

const destroyElement = () => {
    popenevTVisible.value = false;
};

// 导出方法
defineExpose({
    showModal
});
</script>

<style lang="scss" scoped>
</style>